package com.shqcjd.sinopecdemomobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.DefectManageTypeBean;
import com.shqcjd.sinopecdemomobile.model.pojo.EquipmentListBean;
import com.shqcjd.sinopecdemomobile.ui.adapter.EquipmentListAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.WrapContentLinearLayoutManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 设备管理
 */
public class EquipmentListActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.sp_euipment_list_type)
    Spinner spEuipmentListType;
    @BindView(R.id.sp_euipment_list_time)
    Spinner spEuipmentListTime;
    @BindView(R.id.sp_euipment_list_state)
    Spinner spEuipmentListState;
    @BindView(R.id.rv_equipment_list)
    RecyclerView rvEquipmentList;
    @BindView(R.id.sr_equipment_list)
    SwipeRefreshLayout srEquipmentList;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.et_defect_manage)
    EditText etDefectManage;

    private Context context;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private EquipmentListAdapter equipmentListAdapter;
    private List<EquipmentListBean.ItemsBean> mList = new ArrayList<>();

    private int eId = 0;

    List timeList = new ArrayList<String>();
    List stateList = new ArrayList<String>();
    private int timeId = 0, stateId = 0;
    private String strSearch = "";

    List typeList = new ArrayList<String>();
    List<DefectManageTypeBean> tList = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_equipment_list;
    }

    @Override
    public void init() {
        super.init();
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvIncludeTitle.setText("设备管理");




        timeList.add("巡检时间 ▾");
        timeList.add("全部");
        timeList.add("7天内已巡检");
        timeList.add("7天内未巡检");
        ArrayAdapter timeAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner, timeList);
        timeAdapter.setDropDownViewResource(R.layout.item_spinner);
        spEuipmentListTime.setAdapter(timeAdapter);

        stateList.add("巡检类型 ▾");
        stateList.add("全部");
        stateList.add("人工巡检");
        stateList.add("主动巡检");
        ArrayAdapter stateAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner, stateList);
        stateAdapter.setDropDownViewResource(R.layout.item_spinner);
        spEuipmentListState.setAdapter(stateAdapter);

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        srEquipmentList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        spEuipmentListTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                if(position==1){
                    timeId = 0;
                }else if(position==2){
                    timeId = 1;
                }else if(position==3){
                    timeId = 2;
                }
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spEuipmentListState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                if(position==1){
                    stateId = 0;
                }else if(position==2){
                    stateId = 1;
                }else if(position==3){
                    stateId = 2;
                }
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spEuipmentListType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                if(position==1){
                    eId = 0;
                }else if(position>1){
                    eId = tList.get(getListValue(typeList.get(position)+"")).value;
                }
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        etDefectManage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                strSearch = s.toString().replace("#", "%23");
                refreshData();
            }
        });
        getTypeList();
        refreshData();
    }

    private void getTypeList() {
        ApiService.defectManageTypeHttp()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<DefectManageTypeBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData<List<DefectManageTypeBean>> responseData) {
                        tList = responseData.data;
                        typeList.add("设备类型 ▾");
                        typeList.add("全部");
                        for(int i=0; i<responseData.data.size(); i++){
                            typeList.add(responseData.data.get(i).label);
                        }
                        ArrayAdapter arr_adapter = new ArrayAdapter<String>(context, R.layout.item_spinner, typeList);
                        arr_adapter.setDropDownViewResource(R.layout.item_spinner);
                        spEuipmentListType.setAdapter(arr_adapter);

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void refreshData() {
        refreshOrLoadMore();
        srEquipmentList.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore(){
        if(equipmentListAdapter!=null){
            equipmentListAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getData(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p+"");
        map.put("kks", strSearch);
        map.put("pageSize", Config.PAGE_TOTAL+"");
        map.put("equipment_type_id", eId+"");//设备类型id
        map.put("check_time_type", timeId+"");//1代表7天内巡检  2代表7天内未巡检
        map.put("check_type", stateId+"");//0代表全部 1代表任务巡检 2代表随机巡检
        ApiService.equipmentListHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentListBean> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        mList.addAll(responseData.data.items);
                        if (equipmentListAdapter == null) {
                            //设备列表
                            rvEquipmentList.setLayoutManager(new WrapContentLinearLayoutManager(context));
                            equipmentListAdapter = new EquipmentListAdapter(mList,context);
                            rvEquipmentList.setAdapter(equipmentListAdapter);
                            equipmentListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    EquipmentListBean.ItemsBean item = (EquipmentListBean.ItemsBean) adapter.getItem(position);
                                    Intent intent = new Intent(EquipmentListActivity.this, EquipmentInfoActivity.class);
                                    intent.putExtra("kks", item.kks);
                                    startActivity(intent);
                                }
                            });
                            equipmentListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                @Override
                                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                    EquipmentListBean.ItemsBean item = (EquipmentListBean.ItemsBean) adapter.getItem(position);
                                    Intent intent = new Intent(EquipmentListActivity.this, InspectRecordActivity.class);
                                    intent.putExtra("eId", item.id);
                                    startActivity(intent);
                                }
                            });

                            equipmentListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rvEquipmentList.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            int pageSize = responseData.data.total%Config.PAGE_TOTAL==0?responseData.data.total/Config.PAGE_TOTAL:responseData.data.total/Config.PAGE_TOTAL+1;
                                            if (page >= pageSize) {
                                                equipmentListAdapter.loadMoreEnd();
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            equipmentListAdapter.loadMoreComplete();
                        }
                        if(mList.size()==0){
                            rlIsnull.setVisibility(View.VISIBLE);
                        }else{
                            rlIsnull.setVisibility(View.INVISIBLE);
                        }
                        equipmentListAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srEquipmentList.setRefreshing(false);
                    }
                });
    }

    private int getListValue(String str){
        for(int i=0; i<tList.size(); i++){
            if(str.equals(tList.get(i).label)){
                return i;
            }
        }
        return 0;
    }
}
